import {getRequest} from "@/utils/api";


export const initMenu = (router,store) => {
    //先判断路由中是否存在
    if (store.state.routes.length > 0) {
        return
    }

    getRequest('/system/config/menu').then(data => {
        if (data) {
            //格式化router
            let fmtRoutes = formatRoutes(data)
            console.log(fmtRoutes)
            //添加到路由中
            // for (var i = 0;i<fmtRoutes.length;i++) {
            //     router.addRoutes(fmtRoutes[i])
            // }
            router.addRoutes(fmtRoutes)
            //存到store中
            store.commit('initRoutes',fmtRoutes)

            window.sessionStorage.setItem("routes",JSON.stringify(fmtRoutes))
        }
    })
}

export const formatRoutes = (routes) => {
    let fmtRoutes = []
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            iconCls,
            children
        } = router;
        if (children && children instanceof Array) {
            //递归
            children = formatRoutes(children)
        }
        let fmRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
            component(resolve) {
                if (component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'],resolve)
                }else if (component.startsWith('Emp')) {
                    require(['../views/emp/' + component + '.vue'],resolve)
                }else if (component.startsWith('Per')) {
                    require(['../views/per/' + component + '.vue'],resolve)
                }else if (component.startsWith('Sal')) {
                    require(['../views/sal/' + component + '.vue'],resolve)
                }else if (component.startsWith('Sta')) {
                    require(['../views/sta/' + component + '.vue'],resolve)
                }else if (component.startsWith('Sys')) {
                    require(['../views/sys/' + component + '.vue'],resolve)
                }

            }
        }
        fmtRoutes.push(fmRouter)
    })
    return fmtRoutes
}